package cn.tinlan.shopcoin.app.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.ConvertUtil;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.Utils.VerificationCountDownTimer;
import cn.tinlan.shopcoin.base.BaseActivity;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import cn.tinlan.shopcoin.widget.citypicker.GetJsonDataUtil;
import cn.tinlan.shopcoin.widget.citypicker.JsonBean;

/**
 * Created by Mortimer on 2018/12/22. 10:22
 * 佛祖🙏，永无bug。
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.register_person_img)
    ImageView register_person_img;

    @BindView(R.id.register_mobile)
    EditText register_mobile;
    @BindView(R.id.register_verify_tv)
    TextView register_verify_tv;
    @BindView(R.id.register_verify_et)
    EditText register_verify_et;
    @BindView(R.id.register_pwd)
    EditText register_pwd;
//    @BindView(R.id.register_wx)
//    EditText register_wx;
//    @BindView(R.id.register_zfb)
//    EditText register_zfb;

    @BindView(R.id.register_ll_code)
    View register_ll_code;
    @BindView(R.id.register_v_code)
    View register_v_code;
    @BindView(R.id.register_ll_username)
    View register_ll_username;
    @BindView(R.id.register_v_username)
    View register_v_username;
    @BindView(R.id.register_ll_city)
    View register_ll_city;
    @BindView(R.id.register_v_city)
    View register_v_city;

    @BindView(R.id.register_code)
    EditText register_code;
    @BindView(R.id.register_username)
    EditText register_username;
    @BindView(R.id.register_city)
    TextView register_city;

    @BindView(R.id.register_tologin)
    TextView register_tologin;
    @BindView(R.id.register_ok_btn)
    Button register_ok_btn;

//    private String mobile;
    private String cityStr;
    private VerificationCountDownTimer verificationCountDownTimer;


    //    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<String> options0Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_register;
    }




    @Override
    public void initView() {
        super.initView();

        register_person_img.setSelected(false);

        drawableDefaultBar();

        initCountDownTimer();
        bindViewClickEvents();
    }

    private void bindViewClickEvents() {
        register_person_img.setOnClickListener(this);
        register_verify_tv.setOnClickListener(this);
        register_tologin.setOnClickListener(this);
        register_ok_btn.setOnClickListener(this);
        register_city.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_person_img:
                    register_person_img.setSelected(!register_person_img.isSelected());

                    isNewUser(register_person_img.isSelected());
                break;
            case R.id.register_verify_tv:
                getVerify();
                break;
            case R.id.register_tologin:
//                String mobile = register_mobile.getText().toString().trim();
//                Intent intent = new Intent();
//                intent.putExtra("mobile", mobile);
//                setResult(1022,intent);
                finish();
                break;
            case R.id.register_city:
                if (isLoaded) {
                    showPickerView();
                } else {
                    ToastUtils.show("请稍后再试");
                }
                break;
            case R.id.register_ok_btn:
                registerUser();
                break;
        }
    }



    private void isNewUser(boolean isNewUser) {


        if (isNewUser) {
            register_person_img.setImageResource(R.drawable.register_select);
//            register_ll_code.setVisibility(View.GONE);
//            register_v_code.setVisibility(View.GONE);
//            register_ll_username.setVisibility(View.GONE);
//            register_v_username.setVisibility(View.GONE);
//            register_ll_city.setVisibility(View.GONE);
//            register_v_city.setVisibility(View.GONE);
        }else {
            register_person_img.setImageResource(R.drawable.register_normal);
//            register_ll_code.setVisibility(View.VISIBLE);
//            register_v_code.setVisibility(View.VISIBLE);
//            register_ll_username.setVisibility(View.VISIBLE);
//            register_v_username.setVisibility(View.VISIBLE);
//            register_ll_city.setVisibility(View.VISIBLE);
//            register_v_city.setVisibility(View.VISIBLE);
        }

    }

    private void getVerify() {


        String mobile = register_mobile.getText().toString().trim();

        if (mobile.isEmpty() || mobile.length() != 11) {
            ToastUtils.show("请输入正确的手机号");
            return;
        }
        verificationCountDownTimer.timerStart(true);

        EasyHttp.post(Constants.RegisterGetVerify)
                .params("mobile",mobile)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show("获取失败");
                    }
                    @Override
                    public void onSuccess(String s) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("code").equals("2")){
                                ToastUtils.show(jsonObject.getString("data"));
                            }else {
                                ToastUtils.show(jsonObject.getString("data"));
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }) {
                });
    }


    private void initCountDownTimer() {

        if (!VerificationCountDownTimer.FLAG_FIRST_IN &&
                VerificationCountDownTimer.curMillis+60000>System.currentTimeMillis()){
            setCountDownTimer(VerificationCountDownTimer.curMillis+60000-System.currentTimeMillis());
            Log.d("yanzhengma","yanzhengma>>>>>>>>");
            verificationCountDownTimer.timerStart(false);
        }else {
            Log.d("yanzhengma","yanzhengma");
            setCountDownTimer(60000);
        }
    }

    private void setCountDownTimer(final long countDownTimer) {
        verificationCountDownTimer = new VerificationCountDownTimer(countDownTimer,1000) {


            @Override
            public void onTick(long millisUntilFinished) {
                super.onTick(millisUntilFinished);
                register_verify_tv.setEnabled(false);
                register_verify_tv.setText((millisUntilFinished/1000)+"s");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                register_verify_tv.setEnabled(true);
                register_verify_tv.setText("重新获取");
                if (countDownTimer != 60000) {
                    setCountDownTimer(60000);
                }
            }
        };
    }

    private void registerUser() {
        String url = "";
        if (register_person_img.isSelected()) {

            url = Constants.RegisterNewUser;
        }else {
            url = Constants.RegisterNewFFUser;

        }
        Log.d("EasyHttp",url);
        final String tel = register_mobile.getText().toString().trim();

        if (tel.isEmpty() || tel.length() != 11) {
            ToastUtils.show("请输入正确的手机号");
            return;
        }

        if (register_mobile.getText().toString().isEmpty() ||
                register_verify_et.getText().toString().isEmpty() ||
                register_pwd.getText().toString().isEmpty()  ) {
            ToastUtils.show("资料填写不完整，无法提交");
            return;
        }
        String verify = register_verify_et.getText().toString().trim();
        String pwd = register_pwd.getText().toString().trim();
//        String wx = register_wx.getText().toString().trim();
//        String zfb = register_zfb.getText().toString().trim();

        HttpParams params = new HttpParams();
        params.put("mobile",tel);
        params.put("verify",verify);
        params.put("pwd",pwd);
//        params.put("wx",wx);
//        params.put("zfb",zfb);

//        Log.d("EasyHttp",tel+"-"+verify+"-"+pwd+"-"+register_username.getText().toString()+"-");
//        if (!register_person_img.isSelected()) {
            if (register_username.getText().toString().isEmpty() ) {
                ToastUtils.show("资料填写不完整，无法提交1");
                return;
            }
            Log.d("EasyHttp1",tel+"-"+verify+"-"+pwd+"-"+register_username.getText().toString()+"-");
            String code = register_code.getText().toString().trim();
            String username = register_username.getText().toString().trim();
            String city = register_city.getText().toString().trim();
            params.put("username",username);
            params.put("r_code",code+"");
            params.put("city",cityStr+"");


//        }

        EasyHttp.post(url)
                .params(params)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("注册失败");
                    }
                    @Override
                    public void onSuccess(String s) {

                        try {
                          JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getString("code").equals("2")){
                                ToastUtils.show(jsonObject.getString("data"));
                            }else if (jsonObject.getString("code").equals("1")) {

//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
                                        ToastUtils.show(jsonObject.getString("data"));
//                                        mobile = tel;
                                        Intent intent = new Intent();
                                        intent.putExtra("mobile", tel);
                                        setResult(1022,intent);
                                        finish();
//                                    }
//                                });

//                                finish();
                            } else {
                                ToastUtils.show("网络异常");
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }



                    }
                }) {
                });
    }



    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                cityStr = options2Items.get(options1).get(options2);
                String tx = options0Items.get(options1) + cityStr + options3Items.get(options1).get(options2).get(options3);
                register_city.setText(tx);
//                ToastUtils.show(tx);
//                Toast.makeText(JsonDataActivity.this, tx, Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options0Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }




    @Override
    public void initData() {
        super.initData();

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }




    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(JsonDataActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(JsonDataActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(JsonDataActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };



    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
//        options1Items = jsonBean;
//        for (int i = 0; i<jsonBean.size())


        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            options0Items.add(jsonBean.get(i).getPickerViewText());
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    //实现点击屏幕收起键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(ev.getAction()==MotionEvent.ACTION_DOWN){
            View v=getCurrentFocus();
            boolean  hideInputResult =isShouldHideInput(v,ev);
            Log.v("hideInputResult","zzz-->>"+hideInputResult);
            if(hideInputResult){
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) RegisterActivity.this
                        .getSystemService(Activity.INPUT_METHOD_SERVICE);
                if(v != null){
                    if(imm.isActive()){
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            //之前一直不成功的原因是,getX获取的是相对父视图的坐标,getRawX获取的才是相对屏幕原点的坐标！！！
//            Log.v("leftTop[]","zz--left:"+left+"--top:"+top+"--bottom:"+bottom+"--right:"+right);
//            Log.v("event","zz--getX():"+event.getRawX()+"--getY():"+event.getRawY());
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
